package com.tinckay.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tinckay.entity.po.Role;
import com.tinckay.entity.po.RoleMenu;
import com.tinckay.mapper.RoleMapper;
import com.tinckay.mapper.RoleMenuMapper;
import com.tinckay.service.RoleMenuService;
import com.tinckay.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tinckay.service.UserRoleService;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Jean
 * @since 2018-10-30
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleMenuService roleMenuService;

    @Override
    public List<Role> findUserRole(String userName) {
        return baseMapper.findUserRole(userName);
    }

    @Override
    public List<Role> findAllRole(String roleName) {
        return baseMapper.selectList(
                new QueryWrapper<Role>()
                        .lambda()
                        .eq(StrUtil.isNotBlank(roleName), Role::getRoleName, roleName)
                        .orderByDesc(Role::getCreateTime)
        );
    }

    @Override
    public Role findRoleWithMenus(Long roleId) {
        return baseMapper.findRoleWithMenus(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addRole(Role role, Long[] menuIds) {
        role.insert();
        setRoleMenus(role.getId(), menuIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRoles(ArrayList<Long> roleIds) {
        baseMapper.deleteBatchIds(roleIds);
        userRoleService.deleteUserRolesByRoleId(roleIds);
        roleMenuService.deleteRoleMenusByRoleId(roleIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRole(Role role, Long[] menuIds) {
        role.updateById();
        roleMenuService.deleteRoleMenusByRoleId(CollectionUtil.toList(role.getId()));
        setRoleMenus(role.getId(), menuIds);
    }

    private void setRoleMenus(Long roleId, Long[] menuIds) {
        if (ArrayUtil.isNotEmpty(menuIds)) {
            for (Long menuId : menuIds) {
                new RoleMenu(roleId, menuId).insert();
            }
        }
    }


}
